package com.iwop.moto.utils.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.utils.stringUtil.DateFormatter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import com.iwop.moto.utils.stringUtil.Base64;

/**
 * @功能: 支付宝支付
 * @日期: Created by liuwb on 2016/10/31.
 * 支付宝开放平台地址: https://openhome.alipay.com/platform/home.htm
 * 支付宝商户账号:admin@mobom.net
 * 支付宝商户密码:root123#@!
 */
public class AliPayUtil {


    /**
     * 构造授权参数列表
     *
     * @param pid
     * @param app_id
     * @param target_id
     * @return
     */
    public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id) {
        Map<String, String> keyValues = new HashMap<String, String>();

        // 商户签约拿到的app_id，如：2013081700024223
        keyValues.put("app_id", app_id);

        // 商户签约拿到的pid，如：2088102123816631
        keyValues.put("pid", pid);

        // 服务接口名称， 固定值
        keyValues.put("apiname", "com.alipay.account.auth");

        // 商户类型标识， 固定值
        keyValues.put("app_name", "mc");

        // 业务类型， 固定值
        keyValues.put("biz_type", "openservice");

        // 产品码， 固定值
        keyValues.put("product_id", "APP_FAST_LOGIN");

        // 授权范围， 固定值
        keyValues.put("scope", "kuaijie");

        // 商户唯一标识，如：kkkkk091125
        keyValues.put("target_id", target_id);

        // 授权类型， 固定值
        keyValues.put("auth_type", "AUTHACCOUNT");

        // 签名类型
        keyValues.put("sign_type", "RSA");

        return keyValues;
    }

    /**
     * 构造支付订单参数列表
     * @param bizContent
     * @return
     */
    public static Map<String, String> buildOrderParamMap(String bizContent) {
        Map<String, String> keyValues = new HashMap<String, String>();

        keyValues.put("app_id", AliPayComm.APP_ID);
        //keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是测试数据\",\"out_trade_no\":\"" + getOutTradeNo() +  "\"}");
        keyValues.put("biz_content",bizContent );

        keyValues.put("charset",  AliPayComm.CHARSET);

        keyValues.put("method", AliPayComm.ALIPAY_TRADE_APP_MOTHOD);

        keyValues.put("sign_type", AliPayComm.SIGN_TYPE);

        keyValues.put("timestamp", DateFormatter.simpleDateTimeFormat(new Date()));

        keyValues.put("version", AliPayComm.ALIPAY_VERSION);

        keyValues.put("notify_url", Comm.HTTP_URL + AliPayComm.ALIPAY_NOTIFY_URL);

        return keyValues;
    }

    /**
     * 构造支付订单参数信息
     *
     * @param map
     * 支付订单参数
     * @return
     */
    public static String buildOrderParam(Map<String, String> map) {
        List<String> keys = new ArrayList<String>(map.keySet());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }

        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        sb.append(buildKeyValue(tailKey, tailValue, true));

        return sb.toString();
    }

    public static AlipayTradeQueryResponse getAliPayQuery(String orderId){
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",AliPayComm.APP_ID,AliPayComm.PRIVATE_KEY,"json","utf-8",AliPayComm.ALIPAY_PUBLIC_KEY);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map map=new HashMap<>();
        map.put("trade_no",orderId);
        //map.put("out_trade_no",orderId);
        request.setBizContent(JSON.toJSONString(map));
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        AlipayTradeQueryResponse alipayTradeQueryResponse = getAliPayQuery("2016122221001004970222618064");
        Object jsonArray = JSONArray.toJSON(alipayTradeQueryResponse);
        System.out.println(jsonArray);
        System.out.println(alipayTradeQueryResponse.getTradeStatus());
    }

    /**
     * 拼接键值对
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }

    /**
     * 对支付参数信息进行签名
     *
     * @param map
     *            待签名授权信息
     *
     * @return
     */
    public static String getSign(Map<String, String> map, String rsaKey) {
        List<String> keys = new ArrayList<String>(map.keySet());
        // key排序
        Collections.sort(keys);

        StringBuilder authInfo = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            authInfo.append(buildKeyValue(key, value, false));
            authInfo.append("&");
        }

        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));

        String oriSign = sign(authInfo.toString(), rsaKey);
        String encodedSign = "";

        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "sign=" + encodedSign;
    }

    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.decode(privateKey));
            KeyFactory keyf = KeyFactory.getInstance(AliPayComm.ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                    .getInstance(AliPayComm.SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(AliPayComm.CHARSET));

            byte[] signed = signature.sign();

            return Base64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }




}
